<template>
  <d2-container class="page">
    <el-dialog
      width="640px"
      title="物流详情"
      :visible.sync="dialogFormVisible2"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-input
        type="textarea"
        :rows="9"
        placeholder="请输入内容"
        v-model="wulxx"
        class="input-demo-400">
      </el-input>
    </el-dialog>

    <el-dialog
      width="1024px"
      :title="createOrEdit"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" ref="form">
        <el-form-item label="订单编号" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.orderNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="收货地址" :label-width="formLabelWidth">
          <el-input v-model="form.address" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系人" :label-width="formLabelWidth">
          <el-input v-model="form.userName" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="form.telNumber" disabled></el-input>
        </el-form-item>

        <el-divider></el-divider>

        <el-form-item>
          <el-table stripe :data="tableData2" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column label="SKU">
              <template slot-scope="scope">{{ scope.row.skuId }}</template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">{{ scope.row.skuName }}</template>
            </el-table-column>
            <el-table-column label="图片">
              <template slot-scope="scope">
                <img v-bind:src="scope.row.imgUrl" style="width:50%" />
              </template>
            </el-table-column>
            <el-table-column label="数量">
              <template slot-scope="scope">{{ scope.row.quantity }}</template>
            </el-table-column>
            <el-table-column label="单价">
              <template slot-scope="scope">{{ scope.row.unitPrice }}</template>
            </el-table-column>
            <el-table-column label="合计金额">
              <template slot-scope="scope">{{ scope.row.totalAmount }}</template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="快递公司" :label-width="formLabelWidth">
          <el-select v-model="form.code" filterable placeholder="请选择" @change="selectedExpress">
            <el-option
              v-for="item in expressList"
              :key="item.expressCom"
              :label="item.expressComName"
              :value="item.expressCom"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" :label-width="formLabelWidth">
          <el-input v-model="form.logisticsNo"></el-input>
        </el-form-item>
        <el-form-item label="发货时间" :label-width="formLabelWidth">
          <el-input v-model="form.logisticsCreateTime" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modify">快递单号写错了，修改</el-button>
        <el-button type="success" @click="copyOrderDetail">复制订单详情</el-button>
        <el-button type="primary" @click="handleCreateNew('form')">发货</el-button>
        <el-button type="danger" @click="splitOrder()">拆单</el-button>
        <el-button type="warning" @click="restore()">拆错了，恢复到原订单</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- <el-button type="primary" size="mini" @click="showCreateDlg('form')">新建</el-button> -->
    <el-button type="primary" size="mini" @click="getList()">搜索</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>-->
      <el-table-column label="订单编号" width="250">
        <template slot-scope="scope">{{ scope.row.orderNo }}</template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">{{ scope.row.status | statusTranslate }}</template>
      </el-table-column>
      <el-table-column label="合计金额">
        <template slot-scope="scope">{{ scope.row.mdseTotalAmount }}</template>
      </el-table-column>
      <el-table-column label="微信支付">
        <template slot-scope="scope">{{ scope.row.collectedAmount }}</template>
      </el-table-column>
      <el-table-column label="积分支付">
        <template slot-scope="scope">{{ scope.row.collectedVirtualCoin }}</template>
      </el-table-column>
      <el-table-column label="快递公司">
        <template slot-scope="scope">{{ scope.row.logisticsEnterpriseName }}</template>
      </el-table-column>
      <el-table-column label="快递单号" width="200px">
        <template slot-scope="scope">{{ scope.row.logisticsNo[0] }}</template>
      </el-table-column>
      <el-table-column label="运费">
        <template slot-scope="scope">{{ scope.row.freight }}</template>
      </el-table-column>
      <el-table-column label="收件人">
        <template slot-scope="scope">{{ scope.row.receiverInfoVo != undefined ? scope.row.receiverInfoVo.userName : "" }}</template>
      </el-table-column>
      <el-table-column label="联系电话" width="150px">
        <template slot-scope="scope">{{ scope.row.receiverInfoVo != undefined ? scope.row.receiverInfoVo.telNumber : "" }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="200px">
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="showEditDlg(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="success"
            @click="showLogisticsDlg(scope.row)"
          >查物流</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <el-pagination background layout="prev, pager, next" :total="total" @current-change="currentChange" :page-size="25"></el-pagination>
  </d2-container>
</template>

<script>
import * as order from "@/api/shop.order";
import * as clipboard from "clipboard-polyfill";

export default {
  name: "order",
  components: {},
  data() {
    return {
      total: 0,
      // 物流信息
      wulxx: null,
      dialogFormVisible2: false,
      fileList: [],
      tableData: [],
      tableData2: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        code: null,
        logisticsNo: null,
        logisticsCreateTime: null
      },
      formLabelWidth: "100px",
      dialogVisible: false,
      createOrEdit: "",
      listQuery: {
        pageStart: 1,
        pageSize: 25,
        status: "1,2,3,4,5,6,0,71,72"
      },
      expressList: [],
      selectedObj: null
    };
  },
  filters: {
    statusTranslate: function(val) {
      if (val == 2) return "待付款";
      if (val == 4 || val == 5) return "待发货";
      if (val == 6) return "待收货";
      if (val == 71) return "已完成";
    }
  },
  mounted() {
    this.getList();
    this.$route.meta.title = "订单管理";

    order.getExpressList().then(resp => {
      this.expressList = resp.data;
    });
  },
  methods: {
    currentChange(current) {
      this.listQuery.pageStart = current;
      this.getList();
    },

    modify() {
      let input = {
        id: this.form.orderLogisticsId,
        enterpriseName: this.selectedObj != null ? this.selectedObj.expressComName: null,
        enterpriseCode: this.form.code,
        logisticsNo: this.form.logisticsNo
      }
      order.modifyLogistics(input).then(resp => {
        console.log(resp);
        if(resp.success) {
          this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            title: "提示",
            message: "操作成功",
            type: "success",
            duration: 2000
          });

        } else {
          this.$notify({
            title: "提示",
            message: resp.bizMessage,
            type: "success",
            duration: 2000
          });
        }
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    restore() {
      order.shopRestoreSplitPost({orderNo: this.form.orderNo}).then(resp => {
        console.log(resp);
        if(resp.success) {
          this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            title: "提示",
            message: "操作成功",
            type: "success",
            duration: 2000
          });
        } else {
          this.$notify({
            title: "提示",
            message: resp.bizMessage,
            type: "success",
            duration: 2000
          });
        }
      });
    },
    
    splitOrder() {
      if(this.multipleSelection.length == 0) {
         this.$notify({
            title: "提示",
            message: "请选择要拆出那些商品",
            type: "error",
            duration: 2000
          });

          return;
      }

      let input = [];
      this.multipleSelection.forEach(element => {
        input.push({orderNo: this.form.orderNo, skuId: element.skuId});
      });

      order.shopOrderSplitPost(input).then(resp => {
        console.log(resp);
        if(resp.success) {
          this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            title: "提示",
            message: "操作成功",
            type: "success",
            duration: 2000
          });
        } else {
          this.$notify({
            title: "提示",
            message: resp.bizMessage,
            type: "success",
            duration: 2000
          });
        }
      });
    }, 

    copyOrderDetail() {
      let orderInfo = "订单号: " + this.form.orderNo;
      orderInfo += "\r\n收货地址: " + this.form.address;
      orderInfo += "\r\n联系人: " + this.form.userName;
      orderInfo += "\r\n电话: " + this.form.telNumber;
      orderInfo += "\r\n";
      
      this.tableData2.forEach(element => {
        orderInfo += "\r\n商品名称: " + element.skuName;
        orderInfo += "; 数量: " + element.quantity;
      });

      clipboard.writeText(orderInfo);

      this.$notify({
        title: "提示",
        message: "已拷贝到剪切板",
        type: "success",
        duration: 2000
      });

    },

    showLogisticsDlg(row) {
      this.dialogFormVisible2 = true;

      order.getlogisticsInfo({expressNO: row.logisticsNo[0]}).then(resp => {
        console.log(resp);
        if(resp.success && resp.data != null) {
          this.wulxx = "快递公司: " + resp.data.comCompany;
          this.wulxx += "\r\n单号: " + resp.data.expressNO;
          this.wulxx += "\r\n-----------------------------";

          resp.data.data.forEach(element => {
            this.wulxx += "\r\n时间: " + element.time;
            this.wulxx += "\r\n位置: " + element.context;
          });
        } else
          this.wulxx = "没查到物流信息，过会儿再试吧。";
      });
    },

    selectedExpress(val) {
      this.selectedObj = this.expressList.find(item => {
        return item.expressCom === val;
      });
    },

    showCreateDlg(formName) {
      this.dialogFormVisible = true;
      this.createOrEdit = "新建";
      // this.$refs[formName].resetFields();
    },

    showEditDlg(row) {
      this.dialogFormVisible = true;
      this.createOrEdit = "订单详情";
      
      this.form.orderNo = row.orderNo;
      this.form.address =
        row.receiverInfoVo.provinceName +
        ", " +
        row.receiverInfoVo.cityName +
        ", " +
        row.receiverInfoVo.countyName +
        ", " +
        row.receiverInfoVo.detailInfo;

      this.form.userName = row.receiverInfoVo.userName;
      this.form.telNumber = row.receiverInfoVo.telNumber;
      this.form.code = row.logisticsEnterpriseCode;
      this.form.logisticsNo = row.logisticsNo[0];
      this.form.logisticsCreateTime = row.logisticsCreateTime;
      this.form.status = row.status;
      this.form.orderLogisticsId = row.orderLogisticsId;

      this.tableData2 = row.skuInfoList;
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.success) this.downloadPath = response.downloadPath;
    },

    handleCreateNew(formName) {
      let that = this;

      if(that.form.logisticsNo == undefined) {
        that.$notify({
          title: "提示",
          message: "快递公司和快递单号不能为空!",
          type: "error",
          duration: 2000
        });
        return;
      }
      
      if (that.form.status == 6) {
        that.$notify({
          title: "提示",
          message: "这个订单已经发货了!",
          type: "error",
          duration: 2000
        });
        return;
      }

      const set = that.$refs;
      set[formName].validate(valid => {
        if (valid) {
          let obj = {};
          obj.code = that.form.code;
          obj.name = this.selectedObj.expressComName;
          obj.logisticsNo = that.form.logisticsNo;
          obj.orderNo = that.form.orderNo;

          order.deliver(obj).then(resp => {
            if (resp.success) {
              that.dialogFormVisible = false;
              that.getList();
              that.$notify({
                title: "提示",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
            } else {
              that.$notify({
                title: "提示",
                message: resp.bizMessage,
                type: "error",
                duration: 2000
              });
            }
          });
        } else {
          return false;
        }
      });
    },

    getList() {
      order.fetchList(this.listQuery).then(response => {
        if (response.success) {
          this.total = response.data.totalCount;
          this.tableData = response.data.list;
        }
      });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    // handleDelete(row) {
    //   this.$confirm("确认删除么?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning"
    //   }).then(() => {
    //     order
    //       .deleteById(row.id)
    //       .then(() => {
    //         this.getList();
    //         this.$notify({
    //           title: "提示",
    //           message: "操作成功",
    //           type: "success",
    //           duration: 2000
    //         });
    //       })
    //       .catch(() => {
    //         this.$notify({
    //           title: "提示",
    //           message: "操作失败",
    //           type: "error",
    //           duration: 2000
    //         });
    //       });
    //   });
    // }
  }
};
</script>
